<?php

namespace App\Http\Middleware;

use App\Eloquent\User;
use Closure;

class AuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // dd(1);
        //判断用户是否登陆
        if(User::isLogin($request)&&$this->refreshUser($request)){
             return $next($request);
        }

        //记住用户当前访问的地址
        $request->session()->put('prevUrl',$request->fullUrl());
        return redirect()->action('Auth\AuthController@login');         //强制登陆
    }

    /**
     * 刷新session中的用户
     */
    protected function refreshUser($request){
        if(!User::where('id',User::user()->id)->exists()){      //特殊情况,当前用户已经不存在
            return false;
        }
        // dd(455);

        $user = User::findOrFail(User::user()->id);
        // User::logout($request);
        User::loginIn($request, $user);
        return true;
    }
}
